骨干.js和继承方法



我想知道如何在主干中使用函数。视图代码。谁能告诉我这件事该怎么做?我知道扩展只放在var中,我看过extend, prototype, super, parent, baseview和其他花哨的东西。但这只会让我更困惑;)。

var jsHelpers = {
        intVar: 300,
        sum: function(a, b, callback) {
                // do something interesting:
                c = a + b;
                d = c + intVar;
                callback(c);
            } //end sum function
    } //end jsHelpers
    /* somewhere else */
ViewThingy = Backbone.View.extend({
    initialize: function() {
        this.render();
    },
    render: function() {
            var result = jsHelpers.sum(1, 1, function(callbackData) {
                //let's do something with the return stuff:
                this.$el.html(callbackData);
            }); //end jsHelpers
        } // end render
}); //end extend

错误当然是jsHelpers.sum();extend中不可用。

TIA !文斯

var View = Backbone.View.extend({
    hello: function() {
        console.log('hello');
    },
    // You can also override Backbone methods here.
    initialize: function() {
        // Do init code shared by all your views
    }
});
// All the views in your app should extend off this view instead of Backbone.View.
var RandomView = View.extend({
    initialize: function() {
        // Call the parent to do init code.
        View.prototype.initialize.apply(this, arguments);
        this.hello();
    },
    // You can override methods too..
    hello: function() {
        // You can call the parent.
        View.prototype.hello.apply(this, arguments);
    }
});

实际上,这是一个好主意,总是扩展视图,模型,集合和路由器,当你做一个应用程序时,总是有共享的功能,你想要做的,而不是重复相同的代码在你的应用程序的每一个地方。通常对于一个视图,这将是像渲染例程的东西,如渲染模板和渲染子视图-你不会想要在你的应用程序的每个视图再次做那样的逻辑。

通常要共享其他代码,你会使用依赖管理器,如RequireJS或Browserify。但是你也可以有一个全局对象:
window.app = {};

和附加的东西:

window.app.utils = ....;

可以从任何地方访问。拥有一个应用对象是很常见的——例如,你经常会有一个模型来维护应用在app.state的状态。

你可以把你的helper与全局命名空间挂钩,或者让它们成为全局命名空间。

window.jsHelpers = {...}

第二种方式:

jsHelpers = {..} //Remove the var, it'll make jsHelpers a global variable.

出于类似的目的,我使用第一个

最新更新