Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Re : Scope function (method) vs component helper

$
0
0
Along this same line...
I have been looking at the best way to refer to an external mustache helper inside a component for better reuse.

Currently, I load everything with AMD but I think this could be done better inside of a component.
The structure for a shared helper is not defined at all in the documentation.

In my opinion, the documentation leans WAY too much on doing every example in a single script, not referencing a module pattern, which any application of substance is going to be using.

My mustache helper called "/app/components/mustache.helpers/latlon.js" looks like this:

define(['can'],
function (can) {
    mustache.registerHelper("latlon",function (data, options) {
        return [data.lat, data.lon].join(", ");
      });
});

These were all written prior to v2 and can.Component and the basic problem is that I had controllers littered with unrelated Mustache Helper definitions.  I am now looking for a "Best Practice" for referring to these in a Component

So in my component, I was doing this as boilerplate:
define(["can", "mHelpers/latlon"],
function (can) {
    var name = "mycomponent",
        comp = can.Component.extend({
        tag: "app-" + name,
        template: can.view(require.toUrl("comp/" + name + "/" + name + ".mustache.html")),
        scope: { },
        events: { }
    });

    return comp;
});

This loaded and registered the helper, but for a Component based system we really don't want that for various reasons.
Now, I have refactored for Component.

"/app/components/mustache.helpers/latlon.js" becomes:

define(
    return function (data) {
        return data.lat + ", " + data.lon;
      });
});

Mustache helpers lose their dependency on can.js and are used only inside the component (not the supervising controller)
Any component that uses the latlon helper still can without repeating the function, we have a single function to share and it gets load optimized by Require.

The boilerplate changes to:
define(["can", "helpers/latlon"],
function (can, latlon) {
    var name = "mycomponent",
        comp = can.Component.extend({
            tag: "app-" + name,
            template: can.view(require.toUrl("comp/" + name + "/" + name + ".mustache.html")),
            scope: { },
            events: {},
            helpers:{latlon: latlon}
    });

    return comp;
});

{{latlon somecoords}} is still available to the template, but less obtrusively.
Now, if another component needs the helper, RequireJS will hand it the previously loaded one, but it doesn't depend on Can registering it with mustache.  You could do the same thing based on steal, but I am using Require.

Component is a terrific tool for isolating functionality in a much better way than was previously possible with Can.


Viewing all articles
Browse latest Browse all 3491

Trending Articles