Skip to content

Commit

Permalink
fix arguments undefined when extend delegateEvents/undelegateEvents #66
Browse files Browse the repository at this point in the history
  • Loading branch information
popomore committed Nov 28, 2013
1 parent aa9eca4 commit 952ad88
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,9 @@ define(function(require, exports, module) {

// 注册事件代理
delegateEvents: function(element, events, handler) {
var argus = trimRightUndefine(Array.prototype.slice.call(arguments));
// widget.delegateEvents()
if (arguments.length === 0) {
if (argus.length === 0) {
events = getEvents(this)
element = this.element
}
Expand All @@ -131,13 +132,13 @@ define(function(require, exports, module) {
// 'click p': 'fn1',
// 'click li': 'fn2'
// })
else if (arguments.length === 1) {
else if (argus.length === 1) {
events = element
element = this.element
}

// widget.delegateEvents('click p', function(ev) { ... })
else if (arguments.length === 2) {
else if (argus.length === 2) {
handler = events
events = element
element = this.element
Expand Down Expand Up @@ -193,14 +194,16 @@ define(function(require, exports, module) {

// 卸载事件代理
undelegateEvents: function(element, eventKey) {
var argus = trimRightUndefine(Array.prototype.slice.call(arguments));

if (!eventKey) {
eventKey = element
element = null
}

// 卸载所有
// .undelegateEvents()
if (arguments.length === 0) {
if (argus.length === 0) {
var type = DELEGATE_EVENT_NS + this.cid

this.element && this.element.off(type)
Expand Down Expand Up @@ -451,4 +454,15 @@ define(function(require, exports, module) {
return o == null || o === undefined
}

function trimRightUndefine(argus) {
for (var i = argus.length - 1; i >= 0; i--) {
if (argus[i] === undefined) {
argus.pop();
} else {
break;
}
}
return argus;
}

});
21 changes: 21 additions & 0 deletions tests/widget-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,27 @@ define(function(require) {
expect(spy2.called).not.to.be.ok()
expect(spy3.called).not.to.be.ok()
})

it('#66 extend delegateEvents', function() {
var spy = sinon.spy()
var TestWidget = Widget.extend({
events: {
'click p': spy
},
delegateEvents: function(element, events, handler) {
return TestWidget.superclass.delegateEvents.call(this, element, events, handler);
},
undelegateEvents: function(element, eventKey) {
return TestWidget.superclass.undelegateEvents.call(this, element, eventKey);
}
})
var widget = globalVar.widget = new TestWidget({
template: '<div><p></p><ul><li></li></ul><span></span></div>'
}).render()

widget.$('p').trigger('click')
expect(spy.called).to.be.ok()
});
})

it('events hash can be a function', function() {
Expand Down

0 comments on commit 952ad88

Please sign in to comment.