Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Observer on input value triggers the observer callback too soon #979

Closed
emiltamas opened this issue Jul 14, 2014 · 2 comments
Closed

Observer on input value triggers the observer callback too soon #979

emiltamas opened this issue Jul 14, 2014 · 2 comments

Comments

@emiltamas
Copy link
Contributor

JSFiddle here

The observer callback probably gets fired internally when Ractive sets the value to an empty string after being initially undefined. Is this by design? My expectation is that the observer shouldn't trigger when the variable is being initialised.

@Rich-Harris
Copy link
Member

Yes, this is actually part of the design - observer callbacks always fire immediately unless you pass in an options object with {init: false}:

var observer = ractive.observe( 'foo', function ( foo ) {
  // this will NOT be called immediately
}, { init: false });

I wrote a bit about the rationale on this thread - will quote the relevant bit:

As for the init: true default behaviour, browniefed hits the nail on the head - it's not actually an event system, but a data flow system. The mechanism is the same, but the idea is subtly different - it's closer to the world of RxJS and Bacon.js than traditional pub/sub (which in my experience scales poorly), but without using Rx/Bacon primitives. It's designed to enable a form of reactive programming, where any given input state can lead to exactly one output state - to achieve that kind of idempotency the observer has to be called with the initial value.

With pub/sub based systems it's not uncommon to see stuff like this:

// set up some form of data-binding...
model.on( 'change:foo', function ( foo ) {
  view.renderFoo( foo );
});

// ...and initialise to the current value
view.renderFoo( model.get( 'foo' ) );

Observers avoid that kind of redundancy (and because of their clearer intent, it's easier to guard against things like circularity). But of course it's sometimes desirable to use observers in other ways, which is why the init option exists.

@emiltamas
Copy link
Contributor Author

You, Sir, are amazing! That makes sense. I now also see the init option in the documentation.
I initially missed it because it was light-greyed out as an inline comment in the sample source.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants