-
Notifications
You must be signed in to change notification settings - Fork 534
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add once to Utils #186
Add once to Utils #186
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -226,6 +226,33 @@ define( | |
} | ||
}, this); | ||
}; | ||
}, | ||
|
||
// ensures that a function will only be called once. | ||
// usage: | ||
// will only create the application once | ||
// var initialize = utils.once(createApplication) | ||
// initialize(); | ||
// initialize(); | ||
// | ||
// will only delete a record once | ||
// var myHanlder = function () { | ||
// $.ajax({type: 'DELETE', url: 'someurl.com', data: {id: 1}}); | ||
// }; | ||
// this.on('click', utils.once(myHandler)); | ||
// | ||
once: function(func) { | ||
var ran, result; | ||
|
||
return function() { | ||
if (ran) { | ||
return result; | ||
} | ||
ran = true; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. shouldn't this appear after the function has been called? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. will change. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. still needs to be fixed |
||
result = func.apply(this, arguments); | ||
|
||
return result; | ||
}; | ||
} | ||
|
||
}; | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -291,4 +291,14 @@ define(['lib/component', 'lib/utils'], function (defineComponent, utils) { | |
}); | ||
}); | ||
|
||
describe('once()', function () { | ||
it('should only call a function once', function () { | ||
var sum = 0; | ||
var increment = utils.once(function () { sum++; }); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. s/utils/util |
||
increment(); | ||
increment(); | ||
expect(sum).toEqual(1); | ||
}); | ||
}); | ||
|
||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
would add this example to the docs too