Skip to content

Commit

Permalink
Merge pull request #149 from yandex-ui/destroy-with
Browse files Browse the repository at this point in the history
destroyWith in ns.Model
  • Loading branch information
yanann11 committed Aug 26, 2013
2 parents 9d3d4fd + a6afed6 commit 1ab054f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/ns.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,28 @@ ns.Model.prototype._bindEvents = function() {
}
};

/**
* Модель должна удалиться вместе с переданными моделями
* @param { ns.Model | ns.Model[] } models - модель или массив моделей
*/
ns.Model.prototype.destroyWith = function(models) {
if (!Array.isArray(models)) {
models = [models];
}

for (var i = 0, len = models.length; i < len; i++) {
var model = models[i];
if (model instanceof ns.Model) {
// при уничтожении модели, с которой связана текущая - она тоже должна быть уничтожена
model.on('ns-model-destroyed', function() {
ns.Model.destroy(this);
}.bind(this));
} else {
throw new Error("[ns.Model] " + this.id + " destroyWith expected ns.Model or Array of ns.Model in argument");
}
}
};

/**
* Ищет метод в объекте по имени или возвращает переданную функцию
* Нужен для навешивания коллбеков
Expand Down
42 changes: 42 additions & 0 deletions test/spec/ns.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,48 @@ describe('ns.Model', function() {

});


describe('destroyWith', function() {

beforeEach(function() {

ns.Model.define('model1', {
params: {
id: null
}
});
this.model1 = ns.Model.get('model1', {id: 1}).setData({key: 1});

ns.Model.define('model2', {
params: {
id: null
}
});
this.model2 = ns.Model.get('model2', {id: 1}).setData({key: 1});
});

afterEach(function() {
delete this.model1;
delete this.model2;
});

it('should destroy model2 after destroying model1', function() {
this.model2.destroyWith(this.model1);
ns.Model.destroy(this.model1);

expect(ns.Model.find('model2', { id: 1 })).not.to.be.ok();
});

it('should throw error if tried to destroy ns.Model with string', function() {
expect(function() { this.model1.destroyWith('string'); }).to.throwException();
});

it('should throw error if tried to destroy ns.Model with undefined', function() {
expect(function() { this.model1.destroyWith(ns.Model.find('model2', {id: 2})); }).to.throwException();

});
});

});

});

0 comments on commit 1ab054f

Please sign in to comment.