Backbone View: Inherit and extend events from parent

前端 未结 15 803
醉梦人生
醉梦人生 2020-11-30 16:50

Backbone\'s documentation states:

The events property may also be defined as a function that returns an events hash, to make it easier to programmatic

15条回答
  •  感情败类
    2020-11-30 17:15

    I've found a more interesting solutions in this article

    It use of the Backbone’s super and ECMAScript’s hasOwnProperty. The second of its progressives examples works like a charm. Here's a bit a code :

    var ModalView = Backbone.View.extend({
        constructor: function() {
            var prototype = this.constructor.prototype;
    
            this.events = {};
            this.defaultOptions = {};
            this.className = "";
    
            while (prototype) {
                if (prototype.hasOwnProperty("events")) {
                    _.defaults(this.events, prototype.events);
                }
                if (prototype.hasOwnProperty("defaultOptions")) {
                    _.defaults(this.defaultOptions, prototype.defaultOptions);
                }
                if (prototype.hasOwnProperty("className")) {
                    this.className += " " + prototype.className;
                }
                prototype = prototype.constructor.__super__;
            }
    
            Backbone.View.apply(this, arguments);
        },
        ...
    });
    

    You can also do that for ui and attributes.

    This example does not take care of the properties set by a function, but the author of the article offers a solution in that case.

提交回复
热议问题