0

I am refactoring code base based on Knockout.js and have stumped into a problem. The code uses templates as interpolated strings in typescript eg.

var template = `<div title='${Resources.string1}'> ${Resources.string1} </div>`

The problem is that the strings can contain a single quote which sometimes break the proper HTML parsing after it has been compiled to javascript.

var template = `<div title='I have a ' single quote'> I have a ' single quote</div>`

I want to expose the Resources object so that it is visible in all the view models without explicitly adding the resource object to every view model so that I can use it like this

<div data-bind="title: Resource.string1"> ${Resources.string1} </div>

Or is their anything global to which I can bind this resources object and access it from all view models inside my app.

Harshil Lodhi
  • 7,274
  • 1
  • 33
  • 42
  • Probably you can use $root object (http://knockoutjs.com/documentation/binding-context.html) as a container to hold global objects. – TSV Nov 03 '16 at 08:17
  • When you are talking about all view models do you mean they are all sub view models of a main view model or they are individual view models? – Matin Kajabadi Nov 03 '16 at 13:50
  • @Matt.kaaj They are individual view models. – Harshil Lodhi Nov 04 '16 at 18:09
  • You can send it by using your template engine depends on your environment (razor asp.net, blade laravel jade node.js,...) or have it in a separate view model which is loaded on all pages as default. – Matin Kajabadi Nov 04 '16 at 18:33

1 Answers1

1

You can refer to a global variable without any problem.

This one works, here is a demo fiddle.

var Resources = {
  string1: "something here with ' quote"
}
window.Resources = Resources;

ko.applyBindings({});

<div data-bind="text: Resources.string1">
</div>

However, this feels like kind of a hack. I'd rather use some HTML encoding for the resources. See some possibilities here. I'd add a getResource function which would return the requested resource in a properly encoded form.

Community
  • 1
  • 1
Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93