Extending objects with JQuery, Object has no method error
I have this javascript code:
var TodoController = {
init: function() {
$(this).find('input.todo_check').click(function(){
$(this).parents('li.todo').done();
});
}
}
var Todo = {
done: function() {
$(this).toggleClass('done');
}
}
$(document).ready(function() {
$("li.todo").extend(Todo);
$("#todo_list").extend(TodoController).init();
});
When I click on a 'input.todo_check' I expect done() function, on 'li.todo', to be executed. But I get:
=> Uncaught TypeError: Object [object Object] has no method 'done'
What I'm doing wro开发者_运维知识库ng?
This statement should add 'done()' function to "li.todo" elements?:
$("li.todo").extend(Todo);
Thanks. JM
Every time you call $(x)
(for any x
), you get a brand new object. So these two statements:
var $x1 = $("li.todo");
var $x2 = $(this).parents('li.todo');
produce two completely difference objects. So if you do this:
var $x1 = $('li.todo');
$x1.where_is = 'pancakes house?';
And then later do this:
var $x2 = $(this).parents('li.todo');
Then $x2
won't have a where_is
property even if both $x1
and $x2
resolve to the same set of DOM objects.
Also, $.extend
doesn't behave the way you think it does. Calling extend
merges the objects into the first object. So saying:
$(x).extend(Todo);
simply returns Todo
without changing anything whereas:
$(x).extend(Todo, { where_is: 'pancakes house?' });
Adds a where_is
property to Todo
and returns the modified Todo
. That's why you usually see extend
used like this:
options = $.extend({ }, defaults, options);
精彩评论