0

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 wrong?

This statement should add 'done()' function to "li.todo" elements?:

$("li.todo").extend(Todo);  

Thanks. JM

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Here is a working example gist.github.com/jmrepetti/ed6ed6065b59a0b016dc. Tanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.