Last active
August 29, 2015 14:07
-
-
Save mikaelbr/72571151ca0d96aff867 to your computer and use it in GitHub Desktop.
Using Immutable for top-down rendering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Immutable = require('immutable'), | |
React = require('react'), | |
component = require('omniscient'); | |
var data = Immutable.fromJS({ | |
title: 'My list', | |
items: [ 'one', 'two', 'three' ] | |
}); | |
var EditMixin = { | |
changeText: function onChange (e) { | |
// Having access to value through cursors | |
this.props.cursor.update(function () { | |
return 'Swapped text!'; | |
}); | |
// or even something like: | |
// actions.doText(this.props.cursor); | |
} | |
}; | |
var Item = component(EditMixin, function (cursor) { | |
// With Immutable 2.4.0 | |
// return d.span({ onClick: this.changeText }, Immutable.unCursor(cursor)); | |
return React.DOM.li({ onClick: this.changeText }, cursor.deref()); | |
}); | |
var List = component(function (cursor) { | |
return React.DOM.div({}, | |
React.DOM.h1({}, cursor.get('title')), | |
React.DOM.ul({}, | |
cursor.cursor('items').map(function (v, key, itemsCursor) { | |
return Item('item-' + key, itemsCursor.cursor(key)); | |
}).toArray() | |
) | |
); | |
}); | |
var body = document.querySelector('body'); | |
render(); | |
function render () { | |
var cursor = data.cursor(function (newData) { | |
data = newData; | |
render(); | |
}); | |
React.renderComponent(List(cursor), body); | |
} |
Thanks for your comment! This would how ever alter my data structure. Trivial in this contrived case, but can in larger structures not be as trivial. I've updated the original issue with my response: immutable-js/immutable-js#97 (comment)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could update this example by changing your data structure to be:
items: [ {name: 'one'}, {name: 'two'}, {name: 'three'} ]
And then referencing
cursor.get('name')
andcursor.update('name', v => v)
And on line 32, you can replace
itemsCursor.cursor(key)
withitemsCursor.get(key)
-- that also returns a wrapped cursor value for Immutable collections.