2014-02-28 25 views
0

我試圖爲一個Marionette ItemView延遲加載模板,但事情並不按我期望的方式工作。 以下有關如何重寫是getTemplate方法的一些技巧,我做了以下內容:RequireJS - 在Marionette上的延遲加載模板ItemView

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

但輸出是需要方法的函數體。

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

並返回需要方法是不是工作壓力太大:

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

這使我在控制檯中的一些錯誤:

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

看來,getTemplate方法被前返回require已完成。我可以將返回包裝在setTimeout函數中,但這不是一個好的解決方案。

有關如何處理此問題的任何想法?

回答

2

require()用於延遲加載的東西時,它是異步的。返回的值是無關緊要的。你需要的東西是這樣的:

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 
    }); 
} 

異步意味着執行的結果不可立即使用。註釋signal the application...是代碼的佔位符,它將通知應用程序的其他部分,結果實際上可用,並且可以繼續處理。如果你不期待它,這是乏味的,但事情是這樣的。

看看JS Promise API,由許多偉大的圖書館實施,從jQuery到獨立Q library

+0

不錯,它似乎是正確的做法。就像你指出的那樣,我發現了一篇關於這個主題的博客文章,使用promise。 http://www.joezimjs.com/javascript/lazy-loading-javascript-with-requirejs/ – darksoulsong

+0

肯定的承諾是走異步JS的路。對於使用RequireJS進行延遲​​加載,您還可以查看我的項目:[require-lazy](https://github.com/nikospara/require-lazy) –