Skip to content

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

@ashelleyPurdue

Description

@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

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

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!';
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions