Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - Ember.js and RequireJS

Has anyone had much success with RequireJS and Ember.js? Seeing as Ember likes to have its structure assigned to a global object I'm finding that it can really butt heads with Requirejs. Would something like LAB.js work better for Ember?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT (2012-01-30): I pushed a more complete example in a repo on bitbucket.

I have successfully used RequireJS to load Ember.js as well as the datetime addon (github). The Ember namespace itself stays global, but all of my application's data, including my instance of Ember.Application, is kept within modules through RequireJS. I'm also loading the handlebars templates using the 'text!' plugin.

I haven't had any issue yet, but this is not a complete application, more of a proof of concept. Here's how I made it work. I can load my application directly with Safari without the need of a server. You would still need a server to load it with Chrome, which doesn't let JavaScript load files from the filesystem.

1) Because Ember.js uses BPM/Spade, I couldn't use a clone of the repo. Instead I'm wrapping the compiled version within a module:

lib/ember.js:

define(['jquery',
        'plugins/order!lib/ember-0.9.3.js',
        'plugins/order!lib/ember-datetime.js'],
         function() {
             return Ember;
});

Note that this in itself doesn't hide Ember from the global scope. But I'm setting things up so that if, in the future, I'm able to do hide it, every other module which depends on this module will still work as-is.

2) Modules can refer to Ember like so:

app/core.js:

define(['lib/ember'], function(Em) {
    MyApp = Em.Application.create({
        VERSION: "0.0.1"
    });
    return MyApp;
});

Here, "Em" could have been named something else; it doesn't refer directly to the global variable, but comes from the module defined in lib/ember.js.

3) To be accessible by Ember, handlebars have to be registered:

app/templates/my-template.handlebars:

MyApp v{{MyApp.VERSION}}.

app/views/my-view.js:

define(['lib/ember',
        'plugins/text!app/templates/my-template.handlebars'],
        function(Em, myTemplateSource) {

            Em.TEMPLATES["my-template"] = Em.Handlebars.compile(myTemplateSource);

            var myView = Em.View.create({
                templateName: "my-template";
            });

            return myView;
});

4) I'm using require-jquery.js (jQuery and RequireJS bundled together).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...