Charlie
Charlie

Reputation: 10307

CoffeeScript + KnockoutJS Function Binding

I'm using CoffeeScript and KnockoutJS and have a problem getting the values of my view model from within a function.

I have a view model:

window.Application || = {}
class Application.ViewModel 
    thisRef = this
    searchTerm: ko.observable("")
    search: ->
        alert @searchTerm

Which compiles to:

window.Application || (window.Application = {});
Application.ViewModel = (function() {
  var thisRef;
  function ViewModel() {}
  thisRef = ViewModel;
  ViewModel.prototype.searchTerm = ko.observable("");
  ViewModel.prototype.search = function() {
    return alert(this.searchTerm);
  };
  return ViewModel;
})();

This view model is part of a parent view model which exposes it as field. The problem is that I can't get a reference to the child view model. In the search function 'this' is a instance of the parent, which I don't want.

Upvotes: 2

Views: 2080

Answers (2)

Trevor Burnham
Trevor Burnham

Reputation: 77416

In the search function 'this' is a instance of the parent...

That depends on how you call it. If you do

m = new Application.ViewModel
m.search()

then this will be m; if you write

obj = {search: m.search}
obj.search()

then this will be obj.

Anyway, just use CoffeeScript's => operator:

search: =>
    alert @searchTerm

That way, this/@ within search will point to the ViewModel instance.

thisRef will, as Travis says, just point to the class, not the instance.

Upvotes: 5

Travis
Travis

Reputation: 10547

You already have a thisRef object hanging around, use thisRef.searchTerm instead of @searchTerm. I often have that happen when using jQuery...

doSomething = ->
  target = $(@)
  $("#blah").click ->
    target.doSomethingElse()

Since @doSomethingElse() would be bound to the DOM element the click was executed for. Not what I want.

Upvotes: 0

Related Questions