Dan Walmsley
Dan Walmsley

Reputation: 2821

How do I use a constructor in javascript

Here is my problem.

I am using Backbone js and every collection I have defined requires the same check on save or destroy. Except that the destroy success functions need to be passed an element to remove from the page when the destroy succeeds.

I didn't want to copy and paste the same code into every save or destroy method so I created this:

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

And I use it like this:

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

The problem is when success is called I get the following error:

Uncaught TypeError: Object [object Window] has no method '_success'

Any help will be much appreciated. I'm also open to any suggestions on better ways to handle this.

Upvotes: 0

Views: 68

Answers (1)

pdoherty926
pdoherty926

Reputation: 10349

this inside of SaveResponseHandler.success isn't SaveResponseHandler, it's 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/

Upvotes: 1

Related Questions