문제

I'm trying to lazy load a template for a Marionette ItemView but things are not working the way I expected. Following some tips about how to override the getTemplate method, I did the Following:

getTemplate: function () {
    var template = require(['text!templates/login/loginbox-template.html'], function (template) {
        return template;
    });
    return _.template(template);
}

But the output is the function body of the require method.

function localRequire(deps, callback, errback) (... and so on)

And returning the require method is not working too:

getTemplate: function () {
    return require(['text!templates/login/loginbox-template.html'], function (template) {
        return _.template(template);
    });
}

This gives me some errors in the console:

Uncaught RangeError: Maximum call stack size exceeded jquery-1.11.js?v=1393591915026:5801
Uncaught TypeError: Object #<Object> has no method 'slice' 

It seems that the getTemplate method is being returned before require is completed. I could wrap the return in a setTimeout function but this is not by far a good solution.

Any ideas about how to handle this?

도움이 되었습니까?

해결책

When require() is used to lazy-load stuff, it is asynchronous. The returned value is irrelevant. What you need is something like:

getTemplate: function () {
    var template;
    require(['text!templates/login/loginbox-template.html'], function (t) {
        template = t;
        // signal the application that template is resolved; I suggest promises
    });
}

Asynchronous means that the result of the execution is not available immediately. The comment signal the application... is a placeholder for the code that will notify the other parts of your application that the result is actually available and they can continue processing. This is tedious if you were not expecting it, but it is how things are.

Take a look at the JS Promise API, implemented by many great libraries, from jQuery to the standalone Q library.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top