Git Product home page Git Product logo

dsfvaluebinders's Introduction

DSFValueBinders

Swift Package Manager

ValueBinder

A ValueBinder creates a two-way binding object to allow sharing of a value between objects.

This is mildly similar to @Binding in SwiftUI but doesn't rely on SwiftUI - meaning it can be used pretty much anywhere Swift can.

Creating

You can define a binder using the standard initializer.

This initializer also allows you to supply a callback block that gets triggered when the wrappedValue changes.

let countBinder = ValueBinder<Int>(0) { newValue in
   Swift.print("countBinder changed: \(newValue)")
}
...
countBinder.wrappedValue = 4  // triggers the update callback

Registering for change updates

You can hand your ValueBinding object to another class which can supply a block to be called when the ValueBinder wrapped value changes.

class AnotherClass {
   init(_ binder: ValueBinder<Int>) {
      binder.register(self) { newValue in
         Swift.print("Binding detected change: \(newValue)")
      }
   }
}

Additionally, if you hold on to the binder object your class can update the ValueBinder value too!

class AnotherClass {
   let countBinder: ValueBinder<Int> 
   init(_ binder: ValueBinder<Int>) {
      countBinder = binder
      countBinder.register(self) { newValue in
         Swift.print("Binding detected change: \(newValue)")
      }
   }
   
   func userPressed() {
      countBinder.wrappedValue += 1
   }
}

Updating the ValueBinder value

Any object that holds a ValueBinder object can update the wrapped value.

_countBinder.wrappedValue += 1

All objects that have registered for change callbacks will be notified of the change in value.

ValueBinding PropertyWrapper

ValueBinding is a property wrapper implementation for the ValueBinder type. Thanks to Mx-Iris for sharing their implementation.

Example

@ValueBinding var countValue = 0

// Register a block for updates
$countValue.register { newValue in 
   Swift.print("countValue is now \(newValue)")
}

countValue = 4  // triggers the update callback
// prints "countValue is now 4"

// Register for combine updates
$countValue.publisher?.publisher
   .receive(on: DispatchQueue.global(qos: .background))
   .sink { newValue in
      // Do something with 'newValue'
   }
   .store(in: &subscribers)

KeyPathBinder

A KeyPathBinder is a specialization of the ValueBinder that can track a dynamic keypath

// The dynamic property to bind to. This might be (for example) bound to a control from interface builder.
@objc dynamic var state: NSControl.State = .on

// Our binding object
lazy var boundKeyPath: KeyPathBinder<MyViewController, NSControl.StateValue> = {
   return try! .init(self, keyPath: \.buttonState) { newValue in
      Swift.print("boundKeyPath notifies change: \(String(describing: newValue))")
   }
}()

EnumKeyPathBinder

An EnumKeyPathBinder is a keypath binder for observing Swift enum types.

I had a situation where I was tring to use a KeyPathBinder on the size mode for a toolbar which is of type NSToolbar.SizeMode, and it continually failed. However, binding to NSControl.StateValue on a control worked fine.

The result was that NSControl.StateValue, while appearing like an enum is actually a struct, whereas NSToolbar.SizeMode is an enum (specifically, a RawRepresentable). The issue appears when trying to observe enum type changes, so this class is a specialization of KeyPathBinder specifically for observing such enum types.

Combine

Both binder types expose a property publisher which you can hook up to your combine workflow.

If the OS doesn't support Combine, the publisher property will be nil.

let binder = ValueBinder(0) 
...
let cancellable = binder.publisher?.sink { newValue in
   // do something with `newValue`
}

License

MIT License

Copyright (c) 2023 Darren Ford

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

dsfvaluebinders's People

Contributors

dagronf avatar

Stargazers

Thomas Soteros avatar ShikiSuen avatar  avatar Robert Audi avatar thierry avatar

Watchers

 avatar

dsfvaluebinders's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.