【问题标题】:Backbone.js & Inheritance MethodsBackbone.js 和继承方法
【发布时间】:2014-10-04 12:06:49
【问题描述】:

我想知道如何在 Backbone.View 代码中使用函数。有人可以建议/告诉我这是如何正确完成的。我知道扩展只放入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

报错当然是extend中没有函数jsHelpers.sum();。

TIA!文斯

【问题讨论】:

    标签: javascript function class backbone.js extend


    【解决方案1】:
    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);
        }
    });
    

    实际上,在制作应用程序时始终扩展 View、Model、Collection 和 Router 是个好主意,因为您总是希望执行共享功能,以免在应用程序中到处重复相同的代码。通常对于视图,这将是诸如渲染模板和渲染子视图之类的渲染例程之类的东西——您不希望在应用程序的每个视图中再次执行该逻辑。

    通常要共享其他代码,您会使用 RequireJS 或 Browserify 等依赖管理器。但你也可以有一个全局对象:

    window.app = {};
    

    并附上东西:

    window.app.utils = ....;
    

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

    【讨论】:

      【解决方案2】:

      您可以将您的助手挂钩到某个全局命名空间或将它们设为全局。

      window.jsHelpers = {...}
      

      第二种方式:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-25
        • 2021-08-22
        • 2019-06-21
        • 2012-10-18
        • 1970-01-01
        • 2017-01-07
        • 2011-02-27
        • 2010-11-20
        相关资源
        最近更新 更多