vue

package module
v0.0.0-...-937e60b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2016 License: MIT Imports: 3 Imported by: 0

README

gopherjs-vue

VueJS bindings for gopherjs

Usage

Combined the power of Gopherjs and VueJS, you can use golang struct to provide the two-way data-binding context for VueJS, and easily implements the popular browser MVVM models in Go.

Currently ViewModel/Component/Directive/Filter are supported and wrapped in a gopherjs friendly way.

These are the basic rules to use this package:

  • all exported fields of the golang struct would become VueJS Instance's data which can be used in the html to do data binding: v-bind, etc

  • all exported funcs of the golang struct would become VueJS Instance's methods which can be called as html event handler: v-on, etc

  • the golang struct talked above is actually of pointer type and should have an anonymous embeded *js.Object field and the exported fields should have proper js struct tag for bidirectionaly data bindings

for more details please see the examples.

Basic example

gopherjs code:

package main

import (
    "github.com/gopherjs/gopherjs/js"
    "github.com/oskca/gopherjs-vue"
)

type Model struct {
    *js.Object        // this is needed for bidirectional data bindings
    IntValue   int    `js:"integer"`
    Str        string `js:"str"`
}

// this would be recognized as Inc in html
func (m *Model) Inc() {
    m.IntValue += 1
    println("inc called")
}

// this would be recognized as Repeat in html
func (m *Model) Repeat() {
    m.Str = m.Str + m.Str
}

// this would be recognized as Reset in html
func (m *Model) Reset() {
    m.Str = "a string "
}

func main() {
    m := &Model{
        Object: js.Global.Get("Object").New(),
    }
    // field assignment is required in this way to make data passing works
    m.IntValue = 100
    m.Str = "a string"
    // create the VueJS viewModel using a struct pointer
    vue.New("#app", m)
}

html markup:

<!DOCTYPE html>
<html>

<body>
    <div id="app" v-cloak>
        <div>integer: {{ integer }}
            <input v-model="integer"></input>
        </div>
        <div>str: {{ str }} </div>
        <button v-on:click="Inc">Increase</button>
        <button v-on:click="Repeat">Repeat</button>
        <button v-on:click="Reset">Reset</button>
    </div>
    <script type="text/javascript" src="basic.js"></script>
</body>

</html>

compile and run, then there you are :)

Documentation

Overview

Package composite is an higher level wrapper of gopherjs-vue, by providing a more gopher friendly API, this package tries to hide the JavaScript details for VueJS easy usage in GopherJS world.

Package vue provides gopherjs bindings for VueJS. see func `New` and the examples for detailed usage instructions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Delete

func Delete(obj, key interface{})

Vue.delete( object, key )

Arguments:

{Object} object
{String} key
Usage:

Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

func NextTick

func NextTick(cb func())

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update.

func Partial

func Partial(name, definition string)

Vue.partial( id, [definition] ) id String definition String | Node optional Register or retrieve a global partial. The definition can be a template string, a querySelector that starts with #, a DOM element (whose innerHTML will be used as the template string), or a DocumentFragment.

func Set

func Set(obj, key, value interface{})

Vue.set( object, key, value )

Arguments:

{Object} object
{String} key
{*} value
Returns: the set value.

Set a property on an object. If the object is reactive, ensure the property is created as a reactive property and trigger view updates. This is primarily used to get around the limitation that Vue cannot detect property additions.

Types

type Component

type Component struct {
	*ViewModel
}

Component is actually an Extended Vue SubClass, which acts as a Component constructor in VueJS world thus you can use Component.New to create a preConfigured VueJS instance(*ViewModel).

func GetComponent

func GetComponent(name string) *Component

func NewComponent

func NewComponent(
	vmCreator func() (structPtr interface{}),
	templateStr string,
	replaceMountPoint ...bool,
) *Component

NewComponent creates and registers a named global Component

vmCreator should return a gopherjs struct pointer. see New for more details

func (*Component) New

func (c *Component) New() *ViewModel

New create the component instance

func (*Component) Register

func (c *Component) Register(name string) *Component

Register register Component:c in the global namespace

type Directive

type Directive struct {
	*js.Object
	Name string
	// advanced options
	// Custom directive can provide a params array,
	// and the Vue compiler will automatically extract
	// these attributes on the element that the directive is bound to.
	Params []string `js:"params"`
	// If your custom directive is expected to be used on an Object,
	// and it needs to trigger update when a nested property inside
	// the object changes, you need to pass in deep: true in your directive definition.
	Deep bool `js:"deep"`
	// If your directive expects to write data back to
	// the Vue instance, you need to pass in twoWay: true.
	// This option allows the use of this.set(value) inside
	// the directive:If your directive expects to write data back to
	// the Vue instance, you need to pass in twoWay: true.
	// This option allows the use of this.set(value) inside the directive
	TwoWay bool `js:"twoWay"`
	// Passing in acceptStatement:true enables
	// your custom directive to accept inline statements like v-on does
	AcceptStatement bool `js:"acceptStatement"`
	// Vue compiles templates by recursively walking the DOM tree.
	// However when it encounters a terminal directive,
	// it will stop walking that element’s children.
	// The terminal directive takes over the job of compiling the element and
	// its children. For example, v-if and v-for are both terminal directives.
	Terminal bool `js:"terminal"`
	// You can optionally provide a priority number for your directive.
	// If no priority is specified, a default priority will be used
	//  - 1000 for normal directives and 2000 for terminal directives.
	// A directive with a higher priority will be processed earlier than
	// other directives on the same element. Directives with
	// the same priority will be processed in the order they appear in
	// the element’s attribute list, although that order is not
	// guaranteed to be consistent in different browsers.
	Priority int `js:"priority"`
}

func NewDirective

func NewDirective(updater ...func(ctx *DirectiveContext, val *js.Object)) *Directive

func (*Directive) Register

func (d *Directive) Register(name string)

func (*Directive) SetBinder

func (d *Directive) SetBinder(fn func(ctx *DirectiveContext)) *Directive

func (*Directive) SetUnBinder

func (d *Directive) SetUnBinder(fn func(ctx *DirectiveContext)) *Directive

func (*Directive) SetUpdater

func (d *Directive) SetUpdater(fn func(ctx *DirectiveContext, val *js.Object)) *Directive

type DirectiveContext

type DirectiveContext struct {
	*js.Object
	// el: the element the directive is bound to.
	El *js.Object `js:"el"`
	// vm: the context ViewModel that owns this directive.
	Vm *ViewModel `js:"vm"`
	// expression: the expression of the binding, excluding arguments and filters.
	Expression string `js:"expression"`
	// arg: the argument, if present.
	Arg string `js:"arg"`
	// name: the name of the directive, without the prefix.
	Name string `js:"name"`
	// modifiers: an object containing modifiers, if any.
	Modifiers *js.Object `js:"modifiers"`
	// descriptor: an object that contains the parsing result of the entire directive.
	Descriptor *js.Object `js:"descriptor"`
	// params: an object containing param attributes. Explained below.
	Params *js.Object `js:"params"`
}

type ElementDirective

type ElementDirective struct {
	*Directive
}

In some cases, we may want our directive to be used in the form of a custom element rather than as an attribute. This is very similar to Angular’s notion of “E” mode directives. Element directives provide a lighter-weight alternative to full-blown components (which are explained later in the guide).

Element directives cannot accept arguments or expressions, but it can read the element’s attributes to determine its behavior.

A big difference from normal directives is that element directives are terminal, which means once Vue encounters an element directive, it will completely skip that element - only the element directive itself will be able to manipulate that element and its children.

func NewElementDirective

func NewElementDirective(updater ...func(ctx *DirectiveContext, val *js.Object)) *ElementDirective

func (*ElementDirective) Register

func (d *ElementDirective) Register(name string)

type Filter

type Filter struct {
	*js.Object
	Read  interface{} `js:"read"`
	Write interface{} `js:"write"`
}

func NewFilter

func NewFilter(readerfn interface{}) *Filter

using interface{} type here to utilize GopherJS type convertion automatically

func (*Filter) Register

func (f *Filter) Register(name string)

type LifeCycleEvent

type LifeCycleEvent string
const (
	VmInit          LifeCycleEvent = "init"
	VmCreated       LifeCycleEvent = "created"
	VmBeforeCompile LifeCycleEvent = "beforeCompile"
	VmCompiled      LifeCycleEvent = "compiled"
	VmReady         LifeCycleEvent = "ready"
	VmAttached      LifeCycleEvent = "attached"
	VmDetached      LifeCycleEvent = "detached"
	VmBeforeDestroy LifeCycleEvent = "beforeDestroy"
	VmDestroyed     LifeCycleEvent = "destroyed"
)

type Option

type Option struct {
	*js.Object

	// Type: String
	// Restriction: only respected when used in Vue.extend().
	// Details:
	//
	// Allow the component to recursively invoke itself in its template.
	// Note that when a component is registered globally with
	// Vue.component(), the global ID is automatically set as its name.
	//
	// Another benefit of specifying a name option is console inspection.
	// When inspecting an extended Vue component in the console,
	// the default constructor name is VueComponent,
	// which isn’t very informative. By passing in an optional name option to
	// Vue.extend(), you will get a better inspection output so that
	// you know which component you are looking at.
	// The string will be camelized and used as the component’s constructor name.
	Name string `js:"name"`

	// 	Type: Object | Function
	//
	// Restriction: Only accepts Function when used in a component definition.
	//
	// Details:
	//
	// The data object for the Vue instance. Vue.js will recursively convert
	// its properties into getter/setters to make it “reactive”. The object
	// must be plain: native objects, existing getter/setters and prototype
	// properties are ignored. It is not recommended to observe complex
	// objects.
	//
	// Once the instance is created, the original data object can be accessed
	// as vm.$data. The Vue instance also proxies all the properties
	// found on the data object.
	//
	// Properties that start with _ or $ will not be proxied on the Vue
	// instance because they may conflict with Vue’s internal properties and
	// API methods. You will have to access them as vm.$data._property.
	//
	// When defining a component, data must be declared as a function that
	// returns the initial data object, because there will be many instances
	// created using the same definition. If we still use a plain object for
	// data, that same object will be shared by reference across all instance
	// created! By providing a data function, every time a new instance
	// is created, we can simply call it to return a fresh copy of
	// the initial data.
	//
	// If required, a deep clone of the original object can be obtained by
	// passing vm.$data through JSON.parse(JSON.stringify(...)).
	Data interface{} `js:"data"`

	// Type: String | HTMLElement | Function
	// Restriction: only accepts type Function when used in a component definition.
	//
	//Details:
	//
	// Provide the Vue instance an existing DOM element to mount on.
	// It can be a CSS selector string, an actual HTMLElement,
	// or a function that returns an HTMLElement.
	// Note that the provided element merely serves as a mounting point;
	// it will be replaced if a template is also provided,
	// unless replace is set to false. The resolved element will
	// be accessible as vm.$el.
	//
	// When used in Vue.extend, a function must be provided
	// so each instance gets a separately created element.
	// If this option is available at instantiation,
	// the instance will immediately enter compilation;
	// otherwise, the user will have to explicitly call
	// vm.$mount() to manually start the compilation.
	El interface{} `js:"el"`

	// Type: String
	//
	// Details:
	//
	// A string template to be used as the markup for the Vue instance. By
	// default, the template will replace the mounted element. When the replace
	// option is set to false, the template will be inserted into the mounted
	// element instead. In both cases, any existing markup inside the mounted
	// element will be ignored, unless content distribution slots are present
	// in the template.
	//
	// If the string starts with # it will be used as a querySelector and use
	// the selected element’s innerHTML as the template string. This allows the
	// use of the common <script type="x-template"> trick to include templates.
	Template string `js:"template"`

	// 	Type: Boolean
	//
	// Default: true
	//
	// Restriction: only respected if the template option is also present.
	//
	// Details:
	//
	// Determines whether to replace the element being mounted on with the
	// template. If set to false, the template will overwrite the element’s inner
	// content without replacing the element itself.
	Replace bool `js:"replace"`

	// parent
	//
	// Type: Vue instance
	//
	// Details:
	//
	// Specify the parent instance for the instance to be created. Establishes
	// a parent-child relationship between the two. The parent will be
	// accessible as this.$parent for the child, and the child will be pushed
	// into the parent’s $children array.
	Parent *js.Object `js:"parent"`
	// contains filtered or unexported fields
}

Option are used to organize mutiple sub component together to construct VueJS apps or (higher level) components.

func NewOption

func NewOption() *Option

func (*Option) AddMethod

func (o *Option) AddMethod(name string, fn func(vm *ViewModel, args []*js.Object)) *Option

AddMethod adds new method `name` to VueJS intance or component using mixins thus will never conflict with Option.SetDataWithMethods

func (*Option) AddProp

func (c *Option) AddProp(name ...string) *Option

AddProp add props to the genereated VueJS instance (optional)

props is a list/hash of attributes that are exposed to accept data from
the parent component. It has a simple Array-based syntax and
an alternative Object-based syntax that allows advanced configurations
such as type checking, custom validation and default values.

func (*Option) AddSubComponent

func (c *Option) AddSubComponent(name string, sub *Component) *Option

AddComponent add sub component to the genereated VueJS instance (optional)

func (*Option) Mixin

func (c *Option) Mixin(val js.M) *Option

The mixins option accepts an array of mixin objects. These mixin objects can contain instance options just like normal instance objects, and they will be merged against the eventual options using the same option merging logic in Vue.extend(). e.g. If your mixin contains a created hook and the component itself also has one, both functions will be called.

Mixin hooks are called in the order they are provided, and called before the component’s own hooks.

func (*Option) NewComponent

func (o *Option) NewComponent() *Component

func (*Option) NewViewModel

func (o *Option) NewViewModel() *ViewModel

NewViewModel create the VueJS instance for finally use the VueJS instance becomes usable only after this call

func (*Option) On

func (c *Option) On(event string, fn func(vm *ViewModel, args []*js.Object)) *Option

On add EventHandler to VueJS-generated component-oriented event for cross component message passing

func (*Option) OnLifeCycleEvent

func (o *Option) OnLifeCycleEvent(evt LifeCycleEvent, fn func(vm *ViewModel)) *Option

func (*Option) SetDataWithMethods

func (c *Option) SetDataWithMethods(structPtr interface{}) *Option

SetDataWithMethods set data and methods of the genereated VueJS instance based on `structPtr` and `js.MakeWrapper(structPtr)`

type Value

type Value struct {
	/////// Normal value operation as js.Object
	*js.Object

	/////// VueJS wrapped Array Operations
	/////// in fact normal gopherjs slice ops would effect
	/////// the save way
	// Add in the bottom of the array
	Push func(any interface{}) (idx int) `js:"push"`
	// Remove in the bottom of the array
	Pop func() (idx int) `js:"pop"`
	//Add in the front of the array
	Unshift func(any interface{}) (idx int) `js:"unshift"`
	//Remove in the front of the array
	Shift func() (idx int) `js:"shift"`
	//array slice operation
	// index	required,position to add to(remove from),negative means reverse
	// howmany	required,number of items to remove, 0 means no remove
	// items... optional,add new items to the array
	Splice  func(index, howmany int, items ...interface{}) *js.Object `js:"splice"`
	Sort    func(sorter func(a, b *js.Object) int) *js.Object         `js:"sort"`
	Reverse func() *js.Object                                         `js:"reverse"`
}

type Value represents the VueJS wrapped observed Array or Object the wrapped methods can be used to trigger view update. `*Value` is usually returned by calling `ViewModel.Get()`

type ViewModel

type ViewModel struct {
	*js.Object
	///////////////////////////// Instance Properties
	// vm.$data
	// 	Type: Object
	// Details:
	//  The data object that the Vue instance is observing.
	//  You can swap it with a new object.
	//  The Vue instance proxies access to the properties on its data object.
	Data *js.Object `js:"$data"`

	// vm.$el
	//  Type: HTMLElement
	//  Read only
	// Details:
	//  The DOM element that the Vue instance is managing.
	//	Note that for Fragment Instances, vm.$el will
	//  return an anchor node that
	//	indicates the starting position of the fragment.
	El *js.Object `js:"$el"`

	// vm.$options
	//  Type: Object
	//  Read only
	// Details:
	//  The instantiation options used for the current Vue instance.
	//  This is useful when you want to include custom
	//  properties in the options:
	//	 new Vue({
	//	   customOption: 'foo',
	//	   created: function () {
	//	     console.log(this.$options.customOption) // -> 'foo'
	//	   }
	//	 })
	Options *js.Object `js:"$options"`

	// vm.$parent
	//  Type: Vue instance
	//  Read only
	// Details:
	// 		The parent instance, if the current instance has one.
	Parent *js.Object `js:"$parent"`

	// vm.$root
	//  Type: Vue instance
	//  Read only
	// Details:
	// 		The root Vue instance of the current component tree.
	// 		If the current instance has no parents this value will be itself.
	Root *js.Object `js:"$root"`

	// vm.$children
	//  Type: Array<Vue instance>
	//  Read only
	// Details:
	// 	The direct child components of the current instance.
	Children *js.Object `js:"$children"`

	// vm.$refs
	// 	Type: Object
	// 	Read only
	// Details:
	// 	An object that holds child components that have v-ref registered.
	// See also:
	// 	Child Component Refs
	// 	v-ref.
	Refs *js.Object `js:"$refs"`

	// vm.$els
	// 	Type: Object
	// 	Read only
	// Details:
	// 	An object that holds DOM elements that have v-el registered.
	// See also: v-el.
	Els *js.Object `js:"$els"`

	// vm.$watch( expression, callback, [deep, immediate] )
	//  expression String
	//  callback( newValue, oldValue ) Function
	//  deep Boolean optional
	//  immdediate Boolean optional
	// Watch an expression on the Vue instance for changes.
	// The expression can be a single keypath or actual expressions:
	WatchEx func(
		expression string,
		callback func(newVal, oldVal *js.Object),
		deepWatch bool,
	) (unwatcher func()) `js:"$watch"`

	// vm.$eval( expression )
	// 	expression String
	// Evaluate an expression that can also contain filters.
	// assuming vm.msg = 'hello'
	// vm.$eval('msg | uppercase') // -> 'HELLO'
	Eval func(expression string) *js.Object `js:"$eval"`

	// vm.$get( expression )
	// 	expression String
	// Retrieve a value from the Vue instance given an expression.
	// Expressions that throw errors will be suppressed
	// and return undefined.
	Get func(expression string) *Value `js:"$get"`

	// vm.$set( keypath, value )
	// 	keypath String
	// 	value *
	// Set a data value on the Vue instance given a valid keypath.
	// If the path doesn’t exist it will be created.
	Set func(keypath string, val interface{}) `js:"$set"`

	// vm.$add( keypath, value )
	//
	// 	keypath String
	// 	value *
	// Add a root level property to the Vue instance (and also its $data).
	// Due to the limitations of ES5, Vue cannot detect properties directly
	// added to or deleted from an Object,
	// so use this method and vm.$delete when you need to do so. Additionally,
	// all observed objects are augmented with these two methods too.
	Add func(keypath string, val interface{}) `js:"$add"`

	// vm.$delete( keypath )
	// 	keypath String
	// Delete a root level property on the Vue instance (and also its $data).
	Delete func(keypath string) `js:"$delete"`

	// vm.$interpolate( templateString )
	// 	templateString String
	// Evaluate a piece of template string containing
	// mustache interpolations.
	// Note that this method simply performs string interpolation;
	// attribute directives are not compiled.
	//
	// // assuming vm.msg = 'hello'
	// vm.$interpolate('{{msg}} world!') // -> 'hello world!'
	Interpolate func(templateString string) `js:"$interpolate"`

	// Each vm is also an event emitter.
	// When you have multiple nested ViewModels,
	// you can use the event system to communicate between them.
	//
	// vm.$dispatch( event, [args…] )
	//	event String
	// 	args… optional
	//
	// Dispatch an event from the current vm that propagates
	// all the way up to its $root. If a callback returns false,
	// it will stop the propagation at its owner instance.
	Dispatch func(event string, args ...interface{}) `js:"$dispatch"`

	// vm.$broadcast( event, [args…] )
	// 	event String
	// 	args… optional
	//
	// Emit an event to all children vms of the current vm,
	// which gets further broadcasted to their children all the way down.
	// If a callback returns false, its owner instance will not broadcast
	// the event any further.
	Broadcast func(event string, args ...interface{}) `js:"$broadcast"`

	// vm.$emit( event, [args…] )
	// 	event String
	// args… optional
	//
	// Trigger an event on this vm only.
	Emit func(event string, args ...interface{}) `js:"$emit"`

	// vm.$on( event, callback )
	// 	event String
	// callback Function
	//
	// Listen for an event on the current vm
	On func(event string, callback interface{}) `js:"$on"`

	// vm.$once( event, callback )
	// 	event String
	// callback Function
	//
	// Attach a one-time only listener for an event.
	Once func(event string, callback interface{}) `js:"$once"`

	// vm.$off( [event, callback] )
	// 	event String optional
	// callback Function optional
	//
	// If no arguments are given, stop listening for all events;
	// if only the event is given, remove all callbacks for that event;
	// if both event and callback are given,
	// remove that specific callback only.
	Off func(event ...string) `js:"$off"`

	// vm.$appendTo( element|selector, [callback] )
	// 	element HTMLElement | selector String
	// callback Function optional
	// Append the vm’s $el to target element. The argument can be either
	// an element or a querySelector string.
	AppendTo func(elementOrselector string) `js:"$appendTo"`

	// vm.$before( element|selector, [callback] )
	// 	element HTMLElement | selector String
	// callback Function optional
	// Insert the vm’s $el before target element.
	Before func(elementOrselector string) `js:"$before"`

	// vm.$after( element|selector, [callback] )
	// 	element HTMLElement | selector String
	// callback Function optional
	// Insert the vm’s $el after target element.
	After func(elementOrselector string) `js:"$after"`

	// vm.$remove( [callback] )
	// 	callback Function optional
	// Remove the vm’s $el from the DOM.
	Remove func() `js:"$remove"`

	// vm.$mount( [element|selector] )
	// 	element HTMLElement | selector String optional
	// If the Vue instance didn’t get an el option at instantiation,
	// you can manually call $mount() to assign an element to it and
	// start the compilation. If no argument is provided,
	// an empty <div> will be automatically created. Calling $mount()
	// on an already mounted instance will have no effect.
	// The method returns the instance itself so you can chain other
	// instance methods after it.
	Mount func(elementOrselector string) *ViewModel `js:"$mount"`

	// vm.$destroy( [remove] )
	//  remove Boolean optional
	// Completely destroy a vm.
	// Clean up its connections with other existing vms,
	// unbind all its directives and remove its $el from the DOM.
	// Also, all $on and $watch listeners will be automatically removed.
	Destroy func(remove bool) `js:"$destroy"`

	// vm.$compile( element )
	// 	element HTMLElement
	// Partially compile a piece of DOM (Element or DocumentFragment).
	// The method returns a decompile function that tearsdown the directives
	// created during the process.
	// Note the decompile function does not remove the DOM.
	// This method is exposed primarily for
	// writing advanced custom directives.
	Compile func(element string) `js:"$compile"`

	// vm.$addChild( [options, constructor] )
	//  options Object optional
	//  constructor Function optional
	//
	// Adds a child instance to the current instance.
	// The options object is the same in manually instantiating an instance.
	// Optionally you can pass in a constructor created from Vue.extend().
	//
	// There are three implications of
	// a parent-child relationship between instances:
	//  The parent and child can communicate via the event system.
	//  The child has access to all parent assets (e.g. custom directives).
	//  The child, if inheriting parent scope,
	//   has access to parent scope data properties.
	AddChild func(options js.M) `js:"$addChild"`

	// vm.$log( [keypath] )
	//
	// keypath String optional
	// Log the current instance data as a plain object, which is more
	// console-inspectable than a bunch of getter/setters.
	// Also accepts an optional key.
	//
	// vm.$log() // logs entire ViewModel data
	// vm.$log('item') // logs vm.item
	Log func(keypath ...interface{}) `js:"$log"`

	// Defer the callback to be executed after the next DOM update cycle.
	// Use it immediately after you’ve changed some data to
	// wait for the DOM update. This is the same as the global
	// Vue.nextTick, except that the callback’s this context is
	// automatically bound to the instance calling this method.
	NextTick func(cb func()) `js:"$nextTick"`
}

type Vue represents the JavaScript side VueJS instance or VueJS component

func GetVM

func GetVM(structPtr interface{}) *ViewModel

GetVM returns coresponding VueJS instance from a gopherjs struct pointer (the underlying ViewModel data), this function is mainly in gopherjs struct method functions to reference the `VueJS instance`

func New

func New(selectorOrHTMLElement interface{}, structPtr interface{}) *ViewModel

New creates a VueJS Instance to apply bidings between `structPtr` and `selectorOrElementOrFunction` target, it also connects the generated VueJS instance with the `structPtr`, you can use `vue.GetVM` from you code to get the generated VueJS Instance which can be used as `this` for JavaScirpt side.

  • all `exported fields` of the `struct` would become VueJS Instance's data which can be used in the html to do data binding: v-bind, etc

  • all `exported funcs` of the `struct` would become VueJS Instance's methods which can be called as html event handler: v-on, etc

  • the `struct` talked above should have an embeded anonymous `*js.Object` field and `exported fields` should have proper `js struct tag` for bidirectionaly data bindings

  • if the `struct` has no embeded anonymous `*js.Object`, it can only be used for information displaying purpose.

Rules for exported functions usage IMPORTANT!:

  • If your func uses any of the `exported fields`, then DONOT modify any. These can be viewed roughly as `computed attribute` in `VueJS` wourld, with the form of function invocation (invoke).

  • If your func modifies any of the `exported fields`, then DONOT use it in any data `DISPLAYing` expression or directive. They can be used as event handlers (their main use cases).

These rules are required for VueJS dependency system to work correctly.

You can get this *ViewModel instance through `vue.GetVM(structPtr)` which acts as `this` of the VueJS(javascript) side of world

func (*ViewModel) FromJS

func (v *ViewModel) FromJS(obj *js.Object) *ViewModel

FromJS set the corresponding VueJS data model field from obj new data model field will be created when not exist

func (*ViewModel) FromJSON

func (v *ViewModel) FromJSON(jsonStr string) *ViewModel

func (*ViewModel) ToJS

func (v *ViewModel) ToJS() *js.Object

func (*ViewModel) ToJSON

func (v *ViewModel) ToJSON() string

func (*ViewModel) Watch

func (v *ViewModel) Watch(expression string, callback func(newVal *js.Object)) (unwatcher func())

WatchEx using a simpler form to do Vue.$watch

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL