Databinding to an instance of a class works in Chrome, but not any other browser

#729 · open · 1 comments

View on GitHub ↗

ashelleyPurdue

# The scenario I have an index.html page that looks like this: ``` <script src="node_modules/rivets/dist/rivets.bundled.min.js"></script> <body> <div id="messages-block"> <h1>Message: { data.message }</h1> </div> <button onclick="data.changeMessage()"> Change Message </button> </body> <script src="index.js"></script> ``` If my index.js file looks like this, my app behaves correctly in all 3 browsers: ``` // Works as expected in all 3 browsers function MessageBlock() { return { message: 'Hello World!', changeMessage() { this.message = 'You changed the message from a function inside the data object!'; } } } var data = MessageBlock(); rivets.bind(document.querySelector('#messages-block'), { data: data, }); ``` The result looks like this: ![image](https://user-images.githubusercontent.com/8558767/54869509-d7dffc80-4d6f-11e9-8a8f-5dea12cac53d.png) But, if I switch from using a factory function to a class, it stops working in Firefox and Edge. index.js: ``` // Only works in Chrome class MessageBlock { message = 'Hello World!'; changeMessage() { this.message = 'You changed the message from a class!'; } } var data = new MessageBlock(); rivets.bind(document.querySelector('#messages-block'), { data: data, }); ``` ![image](https://user-images.githubusercontent.com/8558767/54869526-2a211d80-4d70-11e9-99d5-5f7ebb38865c.png) # Why would I even want to use a class over a factory function, anyway? I plan to eventually move to Typescript, and I want all of the data object's members to be type-checked. I can do that pretty easily with a class: ``` class MessageBlock { message: string = 'Hello World!'; changeMessage(): void { this.message = 'You changed the message from a class!'; } } ``` But if I want to do the same thing with a factory function, I'd have to violate the DRY principle: ``` interface IMessageBlock { message: string; changeMessage: () => void; } function MessageBlock(): IMessageBlock { return { message: 'Hello World!', changeMessage() { this.message = 'You changed the message from a function inside the data object!'; } } } ```

Comments

abraham-serafino

The problem is here: message = 'Hello World!'; You are trying to use "class properties," which are not supported in Firefox. You should move this to the constructor: class MessageBlock { constructor() { this.message = 'Hello world!'; } ... }