CanJs 3, what is the best way to execute a function on a Component

I want to know what is the best way to execute a function on a Component, within the Components ‘scope’. This function can be any function, a function that adds an item to a list or just makes an ajax call, or it does some math with the components current viewModel or even dom nodes from the view that were added by a jQuery plugin, afterwards the function returns a value.

Something like: Component.addItem(); or Component.requestAjaxData();

I know you can share parts of the viewModel to the parent using can-stache-bindings, but it does not pass functions.

I know that you can trigger a function on a observable change, but that kinda seems hacky to me. Unless I’m doing it wrong. Also this would not return a value.

If anyone needs me to clarify anything please ask! :smiley:

Thanks!

Can you explain what you mean by

I know you can share parts of the viewModel to the parent using can-stache-bindings, but it does not pass functions.

You can pass functions using @at.

I was not aware of @at.

Thanks!

Hey, I am trying here on this jsBin and I am having some difficulties.

It seems as if the function that I am trying to pass to the parent gets executed for some reason and is not properly firing?

@Nothing_New I’m a little confused about what you’re trying to do. Should one of these be this.test2()?

    console.log( "good " + this.test ); //shouldnt this be a string?
    console.log( "good " + this.test() ); //shouldnt this be a valid function?

I am trying to execute a function from InnerComponent on the OuterComponent. So like I am trying to pass a function from the InnerComponent to it’s parent and then executing that function from the parent.

test2() is the function I am trying to pass to the parent, I am just binding it as test()

Thanks!

Ok, I was just confused by

console.log( "good " + this.test ); //shouldnt this be a string?

You’re just expecting this to print something like “good function() { … }”.

I think there are a couple changes that need to be made.

First, you want to use the @ with test2 since that is the property that you want to “return whatever is there”, which is what @ does. It should look like:

{^@test2}="test"

Second, in a DefineMap, if you assign a function as the value it will call that function to get the default value. See http://canjs.com/doc/can-define.types.value.html#value__. if you want a property on a DefineMap to be a function just use

test2: function(){ ... }

Here is an example of your JSBin with these changes made: http://jsbin.com/vazocasisa/1/edit?js,console.

1 Like

Ok, thanks for the tips! This works… I was pretty close :smiley:

Yeah, you were. The ^@ has tripped other people up as well.

1 Like