如何在javascript中使用构造函数

时间:2013-03-20 01:08:50

标签: javascript backbone.js

这是我的问题。

我正在使用Backbone js,我定义的每个集合都需要对save或destroy进行相同的检查。除了销毁成功函数需要传递一个元素,以便在销毁成功时从页面中删除。

我不想将相同的代码复制并粘贴到每个save或destroy方法中,所以我创建了这个:

window.SAVE_TYPE_DESTROY = 'destroy';

window.SaveResponseHandler = function(el,type){
    if (!type){
        this.success = function() {
            this._success();
        };
    }else if (type == window.SAVE_TYPE_DESTROY){
        this.success = function() {
            this._success();
            $(el).remove();
        };
    }

};
SaveResponseHandler.prototype._success = function(model, response, options) {
                if ((response.success * 1) === 0) {
                    persistError(model, {
                        responseText: response.message
                    }, {});
                }
            };
SaveResponseHandler.prototype.error = persistError;

var saveResponseHandler = new SaveResponseHandler();

我这样使用它:

 destroy: function() {
        var el = this.el;
        var model = this.model;
        this.model.destroy(new SaveResponseHandler(el,'destroy'));
    },
    change: function() {
        this.model.set({
            job_category_name: $($(this.el).find('input')[0]).val()
        });
        var viewView = this.viewView;
        this.model.save(null, saveResponseHandler);
    }

问题是调用成功时出现以下错误:

  

未捕获的TypeError:对象[对象窗口]没有方法'_success'

任何帮助将不胜感激。我也对任何有关处理这个问题的更好方法的建议持开放态度。

1 个答案:

答案 0 :(得分:1)

this内的{p> SaveResponseHandler.success不是SaveResponseHandler,而是window

window.SaveResponseHandler = function(el, type) {
    var self = this;

    if (!type) {
        this.success = function() {
            self._success();
        };
    } else if (type == window.SAVE_TYPE_DESTROY) {
        this.success = function() {
            self._success();
            $(el).remove();
        };
    }
};

http://jsfiddle.net/ethagnawl/VmM5z/

相关问题