FreeVice
FreeVice

Reputation: 2697

How to add code to a function outside of its main body?

I want add code to a function, outside of the function and possibly even in an entirely different JS file. Is this possible? How can I do this? Here's a code snippet representing what I've tried so far:

function myViewModel() {
    var self = this;

    this.firstName = ko.observable("Mike");
    this.lastName = ko.observable("Rassel");

    // this was where I was originally making the call
    //myViewModel.fullName = ko.computed(function() {
    //    return self.firstName() + ' ' + self.lastName();
    })
}

// this is where the error is happening 
myViewModel.fullName = ko.computed(function() {
    return self.firstName() + ' ' + self.lastName();

ko.applyBindings(new myViewModel());

More code can be viewed at this JFiddle.

Upvotes: 2

Views: 56

Answers (2)

tapan
tapan

Reputation: 1796

You need to add a function like this: myViewModel.prototype.methodName = function(){}

This will serve as a good introduction to OO JS if you want to learn: http://beardedocto.tumblr.com/post/21920818233/oo-js-in-15mins-or-less

Upvotes: 1

David Mårtensson
David Mårtensson

Reputation: 7600

This is the way to add methods to already defined constructor functions in Javascript.

myViewModel.prototype.newFunctionName = function () {};

http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/

http://timkadlec.com/2008/01/using-prototypes-in-javascript/

Upvotes: 1

Related Questions